<?php

class OdsregistrationformController extends AccessRuleManager
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 
            public function accessRules()
            {
                    return array(
                            array('allow',  // allow all users to perform 'index' and 'view' actions
                                    'actions'=>array('index','view'),
                                    'users'=>array('*'),
                            ),
                            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                                    'actions'=>array('create','update'),
                                    'users'=>array('@'),
                            ),
                            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                                    'actions'=>array('admin','delete'),
                                    'users'=>array('admin'),
                            ),
                            array('deny',  // deny all users
                                    'users'=>array('*'),
                            ),
                    );
            }
        */
        
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($RegistrationID)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($RegistrationID),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
        private function setPaymentRegistration($transRef, $transAmount, $isCash = FALSE){
            $payment = new Amspaymenttransaction();
            
            if ($isCash){
                $payment->isNewRecord=TRUE;
                $payment->TransactionSource = 'EPT';
                $payment->TransactionDate = Date('Y-m-d');
                $payment->TransactionReferenceNumber = $transRef;
                $payment->TransactionCode='EIN';
                $pengkali = Mastertransactioncode::model()->find("TransactionCode ='{$payment->TransactionCode}' and isActive = 1");
                $payment->TransactionAmount=$transAmount * $pengkali->Multiplier;
                $payment->CreatedBy = Yii::app()->user->name;
                $payment->CreatedOn = Date("Y-m-d H:i:s");
                
                $this->saveModel($payment);
                
                $payment->isNewRecord=TRUE;
                $payment->TransactionCode='EON';
                $pengkali = Mastertransactioncode::model()->find("TransactionCode ='{$payment->TransactionCode}' and isActive = 1");
                $payment->TransactionAmount=$transAmount * $pengkali->Multiplier;
                $this->saveModel($payment);
            }else{
                $payment->isNewRecord=TRUE;
                $payment->TransactionSource = 'EPT';
                $payment->TransactionDate = Date('Y-m-d');
                $payment->TransactionReferenceNumber = $transRef;
                $payment->TransactionCode='EIN';
                $pengkali = Mastertransactioncode::model()->find("TransactionCode ='{$payment->TransactionCode}' and isActive = 1");
                $payment->TransactionAmount=$transAmount * $pengkali->Multiplier;
                $payment->CreatedBy = Yii::app()->user->name;
                $payment->CreatedOn = Date("Y-m-d H:i:s");
                $this->saveModel($payment);
            }
        }
        
	public function actionCreate()
	{
                $model=new Odsregistrationform;
                $mReceiverHuman = new ReceiverHuman;
                $mReceiverHumanAtt = new ReceiverHumanAttribute();
                $mReceiverLocation = new ReceiverLocation();
                $mShipperHuman = new ShipperHuman();
                $mShipperHumanAtt = new ShipperHumanAttribute();
                $mShipperLocation = new ShipperLocation();
                $itemDetail = new Odsitemsdetail();
                
                $model->RegistrationDate = Date("Y-m-d H:i:s");
                
                if(isset($_POST['ajax']) && $_POST['ajax']==='client-account-create-form')
                {
                    echo CActiveForm::validate($model);
                    Yii::app()->end();
                }

                if(isset($_POST['Odsregistrationform']))
                {
                    $model->attributes=$_POST['Odsregistrationform'];
                    $mShipperHuman->attributes=$_POST['ShipperHuman'];
                    $mReceiverHuman->attributes=$_POST['ReceiverHuman'];
                    $mShipperHumanAtt->attributes=$_POST['ShipperHumanAttribute'];
                    $mReceiverHumanAtt->attributes=$_POST['ReceiverHumanAttribute'];
                    $itemDetail->attributes=$_POST['Odsitemsdetail'];

                    $model->CreatedBy = Yii::app()->user->name;
                    $model->CreatedOn = Date("Y-m-d H:i:s");

                    $SessionText="";
                    $session = Yii::app()->session;
                    if(!empty ($session['SessionText'])){
                        $SessionText = $session['SessionText'];
                    }
                    
                    $funcCommand = Yii::app()->db->createCommand("select fnGetAutoDocumentNumber('InvHuman', 'HumanID', '{$SessionText}') as 'documentNumber'"); 
                    $arrDocumentNumber = $funcCommand->queryRow(); 
                    $mShipperHuman->HumanID = $arrDocumentNumber['documentNumber'];
                    $model->ShipperHumanID = $mShipperHuman->HumanID;
                    $mShipperHumanAtt->HumanID = $mShipperHuman->HumanID;

                    $funcCommand = Yii::app()->db->createCommand("select fnGetAutoDocumentNumber('InvHuman', 'HumanID', '{$SessionText}') as 'documentNumber'"); 
                    $arrDocumentNumber = $funcCommand->queryRow(); 
                    $mReceiverHuman->HumanID = $arrDocumentNumber['documentNumber'];
                    $model->ReceiverHumanID = $mReceiverHuman->HumanID;
                    $mReceiverHumanAtt->HumanID = $mReceiverHuman->HumanID;
                
                    if($model->validate())
                    {
                            
                            //Auto Generate Document for Table Name = odsregistrationform, ColumnName = RegistrationID 
                            $funcCommand = Yii::app()->db->createCommand("select fnGetAutoDocumentNumber('odsregistrationform', 'RegistrationID', '{$SessionText}') as 'documentNumber'"); 
                            $arrDocumentNumber = $funcCommand->queryRow(); 
                            $model->RegistrationID = $arrDocumentNumber['documentNumber']; 

                            $mShipperHuman->isActive = 1;
                            $mShipperHuman->CreatedBy = Yii::app()->user->name;
                            $mShipperHuman->CreatedOn = Date("Y-m-d H:i:s");

                            $mReceiverHuman->isActive = 1;
                            $mReceiverHuman->CreatedBy = Yii::app()->user->name;
                            $mReceiverHuman->CreatedOn = Date("Y-m-d H:i:s");

                            $mShipperHumanAtt->isActive = 1;
                            $mShipperHumanAtt->CreatedBy = Yii::app()->user->name;
                            $mShipperHumanAtt->CreatedOn = Date("Y-m-d H:i:s");

                            $mReceiverHumanAtt->isActive = 1;
                            $mReceiverHumanAtt->CreatedBy = Yii::app()->user->name;
                            $mReceiverHumanAtt->CreatedOn = Date("Y-m-d H:i:s");

                            $itemDetail->RegistrationID = $model->RegistrationID;
                            $itemDetail->ItemsSequence = 1;
                            $itemDetail->isActive = 1;
                            $itemDetail->CreatedBy = Yii::app()->user->name;
                            $itemDetail->CreatedOn = Date("Y-m-d H:i:s");
                            
                            $this->saveModel($mShipperHuman);
                            $this->saveModel($mReceiverHuman);
                            
                            $this->saveModel($mShipperHumanAtt);
                            $this->saveModel($mReceiverHumanAtt);

                            $model->isActive=1;
                            $this->saveModel($model);
                            
                            $this->saveModel($itemDetail);
                            
                            $this->setPaymentRegistration($model->RegistrationID, $model->TotalAmount, $model->PaymentTypeID==1?TRUE:FALSE);
                            $this->redirect(array('view','RegistrationID'=>$model->RegistrationID));
                    }
                }
                
                $this->render('create',array('model'=>$model,
                    'mReceiverHuman'=>$mReceiverHuman,
                    'mReceiverHumanAtt'=>$mReceiverHumanAtt,
                    'mReceiverLocation'=>$mReceiverLocation,
                    'mShipperHuman'=>$mShipperHuman,
                    'mShipperHumanAtt'=>$mShipperHumanAtt,
                    'mShipperLocation'=>$mShipperLocation,
                    'itemDetail'=>$itemDetail,
                ));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($RegistrationID)
	{
                $model=$this->loadModel($RegistrationID);
                
                $model->LastUpdateBy = Yii::app()->user->name;
                $model->LastUpdateOn = Date("Y-m-d H:i:s");

                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Odsregistrationform']))
		{
			$model->attributes=$_POST['Odsregistrationform'];
			$this->saveModel($model);
			$this->redirect(array('view',
	                    'RegistrationID'=>$model->RegistrationID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($RegistrationID)
	{
                if(Yii::app()->request->isPostRequest)
		{
			try
			{
				// we only allow deletion via POST request
				$this->loadModel($RegistrationID)->delete();
			}
			catch(Exception $e) 
			{
				$this->showError($e);
			}

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Odsregistrationform');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
                $model=new Odsregistrationform('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Odsregistrationform']))
			$model->attributes=$_GET['Odsregistrationform'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Odsregistrationform the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($RegistrationID)
	{
                $model=Odsregistrationform::model()->findByPk(array('RegistrationID'=>$RegistrationID));
		if($model==null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Odsregistrationform $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='odsregistrationform-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function saveModel($model)
	{
		try
		{
			$model->save();
		}
		catch(Exception $e)
		{
			$this->showError($e);
		}		
	}
        
        function showError(Exception $e)
	{
		if($e->getCode()==23000)
			$message = "This operation is not permitted due to an existing foreign key reference.";
		else
			$message = "Invalid operation.";
		throw new CHttpException($e->getCode(), $message);
	}
}
